import { useEffect } from "react";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { isBoolean } from "@/utils/is";

let bpmnElement: any = null;
export default function ElementBaseInfo(props: any) {
	const bpmnInstances = () => (window as any)?.bpmnInstances;
	const schemas: FormSchema[] = [
		{
			label: "流程标识",
			field: "id",
			component: "Input",
			componentProps: {
				placeholder: "请输入流标标识",
				onChange: (val: any, tag: boolean) => updateBaseInfo("id", tag)
			},
			rules: [
				{ required: true, message: "流程标识不能为空", trigger: "blur" },
				{
					pattern: /[a-zA-Z_][-_.0-9a-zA-Z$]*/,
					message: "key 不满足 XML NCName 规则",
					trigger: "blur"
				}
			]
		},
		{
			label: "流程名称",
			field: "name",
			component: "Input",
			componentProps: {
				placeholder: "请输入流程名称",
				onChange: (val: any, tag: boolean) => updateBaseInfo("name", tag)
			},
			rules: [{ required: true, message: "流程名称不能为空", trigger: "blur" }]
		}
	];
	const [registerForm, { resetSchema, setFieldsValue, getFieldsValue }] = useForm({
		schemas,
		showActionButtonGroup: false,
		labelWidth: 120,
		baseColProps: { span: 24 }
	});

	/** Function */

	const resetBaseInfo = () => {
		bpmnElement = bpmnInstances()?.bpmnElement;
		if (!bpmnElement) return;
		resetSchema(
			bpmnElement.businessObject.$type == "bpmn:Process"
				? schemas.map(item => ({
						...item,
						componentProps: {
							...item.componentProps,
							disabled:
								item.field === "id"
									? bpmnElement.businessObject.id !== undefined && bpmnElement.businessObject.id.length > 0
									: false
						}
				  }))
				: [
						{
							label: "ID",
							field: "id",
							component: "Input",
							componentProps: {
								onChange: (val: any, tag: boolean) => updateBaseInfo("id", tag)
							}
						},
						{
							label: "名称",
							field: "name",
							component: "Input",
							componentProps: {
								onChange: (val: any, tag: boolean) => updateBaseInfo("name", tag)
							}
						}
				  ]
		);
		setFieldsValue(bpmnElement.businessObject);
	};

	const updateBaseInfo = async (key: string, tag: boolean) => {
		if (isBoolean(tag) && !tag) return;
		// 触发 elementBaseInfo 对应的字段
		const values = await getFieldsValue();
		bpmnInstances().modeling.updateProperties(bpmnElement, {
			...values,
			di: key === "id" ? { id: `${values[key]}_di` } : ""
		});
	};

	/** Effect */

	useEffect(() => {
		if (props.businessObject) {
			resetBaseInfo();
		}
	}, [props.businessObject]);

	useEffect(() => {
		// 针对上传的 bpmn 流程图时，保证 key 和 name 的更新
		if (props.model?.key) {
			setFieldsValue({
				id: props.model.key,
				name: props.model.name
			});
		}
	}, [props.model?.key]);

	useEffect(() => {
		return () => {
			bpmnElement = null;
		};
	}, []);

	return (
		<div className="panel-tab__content">
			<BasicForm register={registerForm} />
		</div>
	);
}
